package czc.hly.spring.servlet;

import czc.hly.demo.mvc.action.DemoAction;
import czc.hly.spring.annotation.Autowried;
import czc.hly.spring.annotation.Controller;
import czc.hly.spring.annotation.Service;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Administrator on 2018\10\28 0028.
 */
public class DispatcherServlet extends HttpServlet {


    // scanPackage=czc.hly.demo
    // templateRoot=layouts
    //配置文件定位资源
    private Properties contextConfig = new Properties();

    //Bean容器
    private Map<String,Object> beanMap = new ConcurrentHashMap<String,Object>();

    //类名集合
    private List<String> classNames = new ArrayList<String>();




    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("---------- 调用doPost ----------");
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //开始初始化的进程
        //定位
        doLoadConfig(config.getInitParameter("contextConfigLocation"));

        //加载
        doScanner(contextConfig.getProperty("scanPackage"));

        //注册
        doRegistry();
        System.out.println("beanMap:"+beanMap);

        //自动依赖注入

        //在Spring中是通过调用getBean方法才出发依赖注入的
        doAutowired();
//        DemoAction action = (DemoAction)beanMap.get("demoAction");
//        action.query(null,null,"Tom");
        initHandlerMapping();
        
    }

    private void initHandlerMapping() {
    }


    //定位资源
    private void doLoadConfig(String location){
        //定位到resource下的properties文件
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(location.replace("classpath:",""));
        try {
            //载入Properties对象里
            contextConfig.load(is);
            System.out.println("contextConfig:"+contextConfig);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (is != null){
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    //加载
    private void doScanner(String packageName){
        //XXXX绝对路径定位资源
        File classDir = new File("C:\\Program Files\\Apache Software Foundation\\Tomcat 8.0\\webapps\\ROOT\\WEB-INF\\classes\\"+packageName.replaceAll("\\.","/"));
        //获取文件数组
        File[] files = classDir.listFiles();
        for (File file : files){
            if(file.isDirectory()){
                //如果是文件夹-》加上文件夹名进行递归调用doScanner方法
                doScanner(packageName + "." +file.getName());
            }else {
                //如果不是文件夹-》去掉.class后缀加入到集合
                classNames.add(packageName + "." + file.getName().replace(".class",""));
            }
        }

        System.out.println(classNames);


    }

    //注册
    private void doRegistry(){
        if (classNames.isEmpty()){return;}

        try {

            for (String className:classNames){
                //获取Class类《反射》
                Class<?> clazz = Class.forName(className);
                //如果是加上@Controller的类，获取该类的名字并通过lowerFirstCase方法把首字母小写当做Key，通过newInstance方法初始化Bean实例为value
                if (clazz.isAnnotationPresent(Controller.class)){

                    String beanName = lowerFirstCase(clazz.getSimpleName());
                    System.out.println("beanName:"+beanName);

                    beanMap.put(beanName,clazz.newInstance());

                }else if (clazz.isAnnotationPresent(Service.class)){

                    //获取@Service注解的默认值，如果等于"",获取该类的名字并通过lowerFirstCase方法把首字母小写当做Key，通过newInstance方法初始化Bean实例为value
                    Service service = clazz.getAnnotation(Service.class);
                    String beanName = service.value();
                    if("".equals(beanName.trim())){
                        beanName = lowerFirstCase(clazz.getSimpleName());
                    }

                    Object instance = clazz.newInstance();

                    beanMap.put(beanName,instance);

                    Class<?>[] interfaces = clazz.getInterfaces();
                    //获取Service类的接口，并把目前的实现类实例存入接口的value
                    for (Class<?> i :interfaces){
                        beanMap.put(i.getName(),instance);
                    }

                }else{
                    //跳过
                        continue;
                }
            }

        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    //自动注入
    private void doAutowired() {

        if (beanMap.isEmpty()) {
            return ;
        }
        System.out.println(beanMap);
        Set<Map.Entry<String, Object>> s = beanMap.entrySet();

        for (Map.Entry<String,Object> entry:s){
            System.out.println(entry.getValue());
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for (Field field:fields){
                if (!field.isAnnotationPresent(Autowried.class)){continue;}
                Autowried autowried = field.getAnnotation(Autowried.class);

                String beanName = autowried.value().trim();
                if ("".equals(beanName)){
                    beanName = field.getType().getName();
                }
                System.out.println("beanName111："+beanName);
                field.setAccessible(true);
                try {
                    field.set(entry.getValue(),beanMap.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }



    }

    //把String的首字母变成小写
    private String lowerFirstCase(String str){
        char [] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);


    }


}
